﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using System.Dynamic;
using System.Diagnostics;
using Achievement.BLL.Provider;

namespace Achievement.Web.Controllers
{
    [Authorize]
    public class SettingController : Controller
    {
        //
        // GET: /Setting/

        public ActionResult Index()
        {
            string path = Server.MapPath("/");
            string drive = path.Substring(0, path.IndexOf('\\') + 1);
            var drives = DriveInfo.GetDrives();
            var driveInfo = drives.Where(d=>d.Name == drive).FirstOrDefault();
            long freeSpace = 0;
            if (driveInfo != null)
            {
                freeSpace = driveInfo.TotalFreeSpace / 1024 / 1024 / 1024;
            }
            dynamic setting = new ExpandoObject();
            setting.FreeSpace = freeSpace;
            setting.BackupPath = drive + "ChengGuoKuBackup\\" + DateTime.Now.ToString("yyyyMMddhhmmss");
            Process[] process = Process.GetProcessesByName("AchievementBackup");
            string pName = string.Empty;
            if (process.Length > 0)
            {
                pName = process[0].ProcessName;
            }
            setting.ProcessName = pName;
            setting.UserBaseCount = UsersProvider.Instance.GetUserBaseCount();
            return View(setting);
        }

        public ActionResult Backup(string backupPath)
        {
            Process[] process = Process.GetProcessesByName("AchievementBackup");
            if (process.Length == 0)
            {
                using (Process p = new Process())
                {
                    string cmd = Server.MapPath("~/Tools/AchievementBackup.exe");
                    ProcessStartInfo psi = new ProcessStartInfo(cmd, Server.MapPath("/") + " " + backupPath);
                    psi.WindowStyle = ProcessWindowStyle.Hidden;
                    p.StartInfo = psi;
                    p.Start();
                    //p.WaitForExit();
                }
            }
            return Redirect("Index");
        }

        public ActionResult SetUserBaseCount(long txtbaseonline)
        {
            UsersProvider.Instance.SetUserBaseCount(txtbaseonline);
            return Redirect("Index");
        }
    }
}
